import AuthStorage from './authStorage'
import axios from 'axios'
import Rest from './rest'

export default {

  login (username, password) {
    let url = '/login'
    return new Promise((resolve, reject) => {
      axios.post(url, {username}, {
        params: {
          username,
          password
        },
        headers: {
          'Authorization': 'Basic ' + window.btoa(`${username}:${password}`)
        }
      })
      .then(res => {
        let account = res.data
        let token = account.token
        AuthStorage.login({account, token})
        Rest.setBasicAuthorization(account.username, password)
        Rest.setBearerAuthorization(token)
        resolve(res.data)
      })
      .catch(error => {
        reject(error)
      })
    })
  },

  logout () {
    let username = this.getUsername()

    AuthStorage.logout()

    let url = '/logout'
    return new Promise((resolve, reject) => {
      axios.post(url, {username}, {
        params: {
          username
        }
      })
      .then(res => {
        resolve(res.data)
      })
      .catch(error => {
        reject(error)
      })
    })
  },

  isLoggedIn () {
    return AuthStorage.loggedIn()
  },

  get () {
    return AuthStorage.getUser()
  },

  getUsername () {
    let user = AuthStorage.getUser()
    if (user) {
      return user.username || ''
    }
    return ''
  },

  getUser () {
    return AuthStorage.getUser()
  },

  getToken () {
    return AuthStorage.getToken()
  },

  set (account, password) {
    let token = password
    AuthStorage.login({account, token})
  },

  setupRest () {
    if (!this.isLoggedIn()) {
      return false
    }
    let user = this.getUser()
    let token = this.getToken()
    Rest.setBasicAuthorization(user.username, token)
    Rest.setBearerAuthorization(token)
    return true
  }

}
